<template>
  <div class="loginset">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账户设置">
          <el-form ref="form" label-width="100px" :model="form" :rules="rules">
            <el-form-item label="姓名:" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input v-model="form.password" type="password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sumitUpdate">更新</el-button>
              <el-button @click="$router.push('/employees')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <component
            :is="'info'"
            :user-info="otherInfo"
            :info-update="infoUpdate"
          />
          <!-- 拷贝数据传递给子组件 子组件更新完数据再传递过来 -->
        </el-tab-pane>
        <el-tab-pane label="岗位详情" lazy>
          <component :is="'Jobs'" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser } from '@/api/user'
import { sysUserPut } from '@/api/employees'
export default {
  components: {
    Info: () => import('./components/Info.vue'),
    Jobs: () => import('./components/Jobs.vue')
  },
  data() {
    return {
      id: this.$route.params.id,
      form: {
        username: '',
        password: ''
      },
      userInfo: '',
      otherInfo: '',
      rules: {
        username: [{ required: true, message: '必填', trigger: 'blur' }],
        password: [{ required: true, message: '必填', trigger: 'blur' }]
      }
    }
  },
  async created() {
    const { data } = await sysUser(this.id)
    // console.log(res)
    this.userInfo = data
    // 定义一个当前数据的拷贝
    this.otherInfo = JSON.parse(JSON.stringify(data))
    this.form.username = data.username
  },
  methods: {
    sumitUpdate() {
      this.$refs.form.validate(async(val) => {
        if (val) {
          await sysUserPut({ ...this.userInfo, ...this.form })
          this.otherInfo.username = this.form.username // 当前数据更新时,需要同步到子组件
          this.$message.success('更新成功')
        }
      })
    },
    infoUpdate(val) {
      // 接收到子组件更新的数据, 同步到姓名 和 userInfo
      this.form.username = val.username
      this.userInfo = JSON.parse(JSON.stringify(val))
    }
  }
}
</script>

<style lang="scss" scoped>
.loginset {
  padding: 15px;
  .el-form-item {
    margin-right: 800px;
  }
}
</style>
